<?php
namespace Common\Controller;
use Common\Org\Login\WxLogin;
use Think\Controller;
use Think\Exception;
use Think\Verify;
use Common\Org\Chat\WeiXin;

class CommonController extends Controller{
    protected $uid;
    protected $user_type;
    protected $returnurl;
    protected $input;//数据验证类实例
    private $apptype = 1;
    protected $location = '';//当前经纬度 22.5656780000,114.1058490000
    protected $address = '';//当前地址信息

    protected function _initialize(){
        $this->uid = session('uid');
        $user_location = session('user_location');
        if($user_location){
            $this->location = $user_location;
        }
        if(MODULE_NAME == 'Wap' && CONTROLLER_NAME == 'Index' && ACTION_NAME == 'index'){
            $address = session('user_address');
            if($address){
                $this->address = $address;
                $this->assign('addressTitle',$address);
            }
        }

        $this->getSiteStatus();

        //异常处理
        set_exception_handler(function($exception){
            file_put_contents('systemerror.log',toDate(NOW_TIME,'Y-m-d H:i:s').":".$exception->getMessage()."\n",FILE_APPEND);//记录系统错误日志
            if(IS_AJAX){
                $this->returnData('系统错误');
            } else {
                toErrorPage();
            }
        });

        $this->initUrl();
        
        if(MODULE_NAME == 'Wap'){
            if(isWeiXinBrowser()){
                $this->dealWx();
                if((CONTROLLER_NAME == 'Index' && ACTION_NAME == 'index' && empty($this->address)) || (CONTROLLER_NAME == 'Index' && ACTION_NAME == 'detail')){
                    $arr = $this->getSignPackage();
                    $this->assign('appId',$arr['appId']);
                    $this->assign('timestamp',$arr['timestamp']);
                    $this->assign('nonceStr',$arr['nonceStr']);
                    $this->assign('signature',$arr['signature']);
                }
            }
        }
    }

    /*
     * 用于登录返回的url初始化
     */
    protected  function initUrl(){
        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        $this->returnurl = base64_encode($url);

        $this->assign("THIS_URL",$this->returnurl);
    }

    /**
     * 获取站点状态
     */
    private function getSiteStatus(){
        if(MODULE_NAME == 'Wap'){
            $alias = 'wx_status';
        }
        $status = D('Admin/Base')->getSettingConfig($alias);
        if($status == 2){
            exit("<h3 style='text-align: center;padding-top: 400px;'>该站点正在维护中</h3>");
        }
    }

    /**
     * 微信用户处理(微信授权)
     */
    private function dealWx(){
        if(empty($this->uid)){
            $code = $_GET['code'];
            if($code){
                $data = https_request("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".C("APPID")."&secret=".C("APPSECRET")."&code=".$code."&grant_type=authorization_code");//通过code换取网页授权access_token
                $result = json_decode($data,true); //对JSON格式的字符串进行编码
                $uid = D('Wap/Info')->reg($result['openid'],$result['access_token']);
                if($uid){
                    $this->uid = $uid;
                    session('uid',$uid);
                }
            }else{
                $url = C('TMPL_PARSE_STRING.__WAP__').'/Index/index';
                redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".C("APPID")."&redirect_uri=".urlencode($url)."&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
            }
        }
    }

    /*
     * 是否登录判断
     */
    protected function isLogin(){
        if(session('?uid')){
            return true;
        } else {
            return false;
        }
    }

    public function return_iframe(){
        $data = I('get.ret');
        $data = base64_decode($data);
        $callback = I('get.callback');
        echo '<script type="text/javascript">document.domain = "'.DOMAIN_SUFFIX.'";window.parent.'.$callback.'('.$data.'); </script>';
    }

    public function uploadredirect(){
        $this->display(COMMON_TPL_PATH.'Upload/redirect');
    }

    public function jqueryuploadredirect(){
        $this->display(COMMON_TPL_PATH.'Upload/jqueryuploadredirect');
    }

    /**
     * 生成图片验证码
     */
    public function buildImageVerify(){
        $width = I('get.width',80,'intval');
        $height = I('get.height',30,'intval');
        $font = I('get.font',16,'intval');
        $verify = new Verify();
        $verify->_entry(2,1,$width,$height,$font);
    }

    /**
     * @param string $verify 图片验证码
     * 图片验证码验证
     */
    public function checkImageVerify($type=0){
        $code = I('post.verify',0,'trim');
        empty($code) && $this->ajaxReturn(array('info'=>'请输入验证码！','status'=>0),'json');
        $result = check_verify($code,2);

        if($result){
            empty($type) && $this->ajaxReturn(array('status'=>1,'info'=>'验证码正确'));
        }else{
            $this->ajaxReturn(array('status'=>0,'info'=>'验证码错误'));
        }
    }

    protected function checkInput($dataVerify){
        $result = $this->input->data($dataVerify)->check();

        if($result['error']){
            $this->ajaxReturn(array('info'=>$result['error'],'status'=>$result['status']),'json');
        }
    }

    /**
     * ajaxReturn 用于简单的返回数据信息
     * @param $info 提示信息
     * @param int $status 状态
     * @param string $data 返回的数据
     */
    public function returnData($info,$status=0,$data=''){
        $this->ajaxReturn(array('data'=>$data,'info'=>$info,'status'=>$status));
    }

    public function _empty(){
        toErrorPage();
    }

    public function epage(){
        $this->display(COMMON_TPL_PATH.'/Common/epage');
    }

    /**
     * 获取经纬度
     */
    public function getLocation(){
        $address = I('get.address','','trim');

        if(empty($address)){
            $this->returnData('地址不能为空');
        }
        try{
            $addressArr = getAddressLocation($address);
            if(empty($addressArr)){
                $this->returnData('请填写正确的地址');
            }

            $this->returnData('ok',1,$addressArr);
        } catch(Exception $e){
            $this->returnData('请填写正确的地址');
        }
    }

    /**
     * 获取地址
     * @return mixed
     */
    public function getAddress(){
        $lat = I('get.lat');
        $lng = I('get.lng');
        $address = getAddressByLocation($lat.','.$lng);
        $this->location = $lat.','.$lng;
        session('user_location',$lat.','.$lng);
        if($address){
            session('user_address',$address);
            $this->address = $address;
            $this->returnData('',1);
        }else{
            $this->returnData('',2);
        }
    }

    /**
     * 获取签名包
     * @return array
     */
    protected function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);
        $signPackage = array(
            "appId"     => C('APPID'),
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "signature" => $signature,
        );
        return $signPackage;
    }

    /**
     * 生成随机字符串
     * @param int $length
     * @return string
     */
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取票据
     * @return mixed
     */
    private function getJsApiTicket() {
        $data = '';//S(C('DB_PREFIX').'_jsapi_ticket');

        if(!$data) {
            $wx = new WeiXin(C('APPID'),C('APPSECRET'));
            //if(S(C('DB_PREFIX').'_accessToken')){
            //    $accessToken = S(C('DB_PREFIX').'_accessToken');
            //}else{
                $accessToken = $wx->getAccessToken();
                S(C('DB_PREFIX').'_accessToken',$accessToken,7200);
            //}
            if($this->apptype==2){
                // 如果是企业号用以下 URL 获取 ticket
                $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            }else{
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            }

            $res = json_decode(https_request($url));
            $ticket = $res->ticket;
            if ($ticket) {
                S(C('DB_PREFIX').'_jsapi_ticket',$ticket,7200);
            }
        } else {
            $ticket = $data;
        }

        return $ticket;
    }
}
?>